package fr.umlv.ig.xml;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import fr.umlv.ig.model.Itinerary;
import fr.umlv.ig.model.Line;
import fr.umlv.ig.model.MetroModelImpl;
import fr.umlv.ig.model.Station;
public class MetroModelFactory extends DefaultHandler {
	
	private MetroModelImpl metroModel = new MetroModelImpl();
	
	private Line currentLine;
	private Itinerary currentItinary;
	private Map<String, Station> currentStations;
	
	private MetroModelFactory() {
		
	}
	
	public static MetroModelFactory newInstance() throws ParserConfigurationException, SAXException, IOException {
		MetroModelFactory metroModelFactory = new MetroModelFactory();
		SAXParserFactory saxParser = SAXParserFactory.newInstance();
		SAXParser parser = saxParser.newSAXParser();
		parser.parse("file.xml", metroModelFactory);
		return metroModelFactory;
	}
	

	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {

		if("line".equals(qName)) {
			currentLine= new Line(attributes.getValue("id"));
				metroModel.addLine(currentLine);
			currentStations = new HashMap<String, Station>();
		}
		if("station".equals(qName)) {
			String name = attributes.getValue("name");
			int x = Integer.parseInt(attributes.getValue("x"));
			int y = Integer.parseInt(attributes.getValue("y"));
			
			Station station = new Station(name, x,y );
			metroModel.addStation(currentLine, station);
			currentStations.put(station.getName(), station);
		}
		if("itinerary".equals(qName)) {
			Itinerary itinerary = new Itinerary(
					(currentStations.get(attributes.getValue("begin"))), 
					(currentStations.get(attributes.getValue("end"))));
			metroModel.addItinerary(currentLine, itinerary); 
		}
		
		if("edgeConfig".equals(qName)) {
			int id = Integer.parseInt(attributes.getValue("itinary"));
			currentItinary = currentLine.getItinerary(id);
		}
		
		if("edge".equals(qName)) {
			//first direction
			Station station = currentStations.get(attributes.getValue("station"));
			Station nextStation = currentStations.get(attributes.getValue("next"));
			metroModel.addNextStation(currentLine, currentItinary.getEnd(), station, nextStation);
			//second direction
			metroModel.addNextStation(currentLine, currentItinary.getStart(), nextStation,station );
		}
	}
	

	
	public MetroModelImpl getMetroModelImpl() {
		return metroModel;
	}
	
	@Override
	public void endDocument() throws SAXException {
		
	}
}
